<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">订单统计</span>
        <div>
          <el-check-tag
            :checked="current == item.value"
            v-for="(item, index) in options"
            :key="index"
            style="margin-right: 8px"
            @click="handleChoose(item.value)"
          >
            {{ item.text }}
          </el-check-tag>
        </div>
      </div>
    </template>

    <div
      id="chart"
      ref="el"
      style="width: 100%; height: 300px"
    ></div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";

import * as echarts from "echarts";

import { getStatistics3 } from "~/api/index.js";

import { useResizeObserver } from "@vueuse/core";

const current = ref("week"); // 默认显示近一周

const options = [
  {
    text: "近1个月",
    value: "month",
  },
  {
    text: "近1周",
    value: "week",
  },
  {
    text: "近24小时",
    value: "hour",
  },
];

const handleChoose = (type) => {
  current.value = type;
  getData();
};

var myChart;
onMounted(() => {
  var chartDom = document.getElementById("chart");
  if (chartDom) {
    // 这里解决无权限显示图表时的报错问题
    myChart = echarts.init(chartDom);
    getData();
  }
});

// 因为组件有keep-alive页面缓存，所以图表没有出现白屏的情况
// 如果当前组件被销毁，有时候会出现白屏
// 销毁页面的时候把图标释放掉，没有释放的话，就会出现白屏的情况，这个
// 问题只有在打包之后才会看到
onBeforeUnmount(() => {
  // 销毁图表实例
  if (myChart) echarts.dispose(myChart);
});

function getData() {
  let option = {
    xAxis: {
      type: "category",
      data: [], // x轴数据
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [], // y轴数据
        type: "bar",
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180,180,180,0.2)",
        },
      },
    ],
  };

  // 图表加载动画
  myChart.showLoading();
  getStatistics3(current.value)
    .then((res) => {
      console.log("图表请求结果：", res);
      option.xAxis.data = res.x;
      option.series[0].data = res.y;
      myChart.setOption(option);
    })
    .finally(() => {
      myChart.hideLoading();
    });
}

// 监听窗口缩放
const el = ref(null);
useResizeObserver(el, (entries) => {
  // console.log("监听窗口缩放：",entries);
  if (myChart) {
    myChart.resize();
  }
});
</script>

<style></style>
